package com.xhl.config;

import com.xhl.entity.FieldErrorVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 系统异常处理，500错误
     */
    @ExceptionHandler(value = {Exception.class,Throwable.class})
    public Object exceptionHandler(Throwable e, HttpServletRequest req, HttpServletResponse response) throws Exception {
        log.error("请求URI={}，系统内部异常={}",req.getRequestURI(),e);
        return e;
    }


    /**
     * 业务自定义系统异常处理
     */
    //@ExceptionHandler(value = {ServiceException.class})
    public Object serviceExceptionHandler(Exception e,HttpServletRequest req) throws Exception {
        String msg=e.getMessage();
        log.error("请求URI={}，业务自定义系统异常信息={}",req.getRequestURI(), msg);
        return true;
    }

    /**
     * 校验参数异常，显示输出具体字段错误列表
     */
    @ExceptionHandler(value= BindException.class)
    public Object validatorbindException(BindException e,HttpServletRequest req){
        List<FieldErrorVO> fieldErrorVos=new ArrayList<FieldErrorVO>();
        StringBuilder msg=new StringBuilder();
        try {
            BindingResult bindingResult=e.getBindingResult();
            if(bindingResult.hasErrors()) {
                List<FieldError> fieldErrors=bindingResult.getFieldErrors();

                FieldErrorVO fieldErrorVo;
                for (FieldError fieldError:fieldErrors) {
                    fieldErrorVo=new FieldErrorVO(fieldError.getField(),fieldError.getDefaultMessage());
                    log.info("错误信息字段={}",fieldErrorVo);
                    fieldErrorVos.add(fieldErrorVo);
                    msg.append(", ").append(fieldError.getDefaultMessage());
                }
                msg.deleteCharAt(0);
            }
        } catch (Throwable  tx) {
            log.error("转换校验参数异常",tx);
        }
        Map<String, Object> msgMap=new HashMap<String, Object>();
        msgMap.put("success", false);
        msgMap.put("code", "500");
        msgMap.put("msg", fieldErrorVos.get(0));
        return msgMap;
    }


}
